package logic

import (
	"api/model/order_food_goods"
	"api/service"
	"context"
	"fmt"
	"github.com/zeromicro/go-zero/core/stores/sqlx"

	"api/internal/svc"
	"api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type OrderFoodUpdateGoodsStatusLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewOrderFoodUpdateGoodsStatusLogic(ctx context.Context, svcCtx *svc.ServiceContext) *OrderFoodUpdateGoodsStatusLogic {
	return &OrderFoodUpdateGoodsStatusLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *OrderFoodUpdateGoodsStatusLogic) OrderFoodUpdateGoodsStatus(req *types.RequestOrderFoodUpdateStatus) (resp *types.ResponseMsg, err error) {
	conn := sqlx.NewMysql(l.svcCtx.Config.DataSource)
	goodsModel := order_food_goods.NewOrderFoodGoodsModel(conn)

	busService := service.NewBusinessService(l.ctx, l.svcCtx)
	bus := busService.GetLoginBusinessInfo()

	goods, err := goodsModel.FindOne(l.ctx, req.Id, bus.Id)

	if goods == nil || goods.Status == req.Status {
		fmt.Println(err.Error())
		return service.ReturnError()
	}

	err = goodsModel.UpdateStatus(l.ctx, &order_food_goods.OrderFoodGoods{
		Id:         req.Id,
		Status:     req.Status,
		BusinessId: bus.Id,
	})

	if err != nil {
		fmt.Println(err.Error())
		return service.ReturnError()
	}

	// 保存商品至redis
	redis := l.svcCtx.RedisPool.Get()
	defer redis.Close()

	goodsService := service.NewOrderFoodService(l.ctx, l.svcCtx)

	if req.Status == 1 {
		// 商品上架
		goods, _ := goodsModel.FindOne(l.ctx, req.Id, bus.Id)
		if goods != nil {
			goodsService.SaveGoods(redis, bus.Id, req.CategoryId, &service.OrderFoodGoods{
				Id:             req.Id,
				Title:          goods.Title,
				Price:          goods.Price,
				Img:            goods.Img,
				Specifications: goods.Specifications,
				Properties:     goods.Properties,
				Jialiao:        goods.Jialiao,
				Des:            goods.Des,
			})
		}

	} else {
		// 商品下架
		goodsService.DelGoods(redis, bus.Id, req.CategoryId, req.Id)
	}

	return service.ReturnOk()
}
